package RMBCaseConversion.otherTeam;
import java.math.BigDecimal;

public class RMBUpToDown2 {
    String upper;

    public RMBUpToDown2(String RMB){
        upper = RMB;
    }

    //大写转小写
    public String UpperToNum(){
        String[] token = upper.split("圆|元");
        String IntegerPart = token[0];
        String DecimalPart = token.length > 1? token[1] : "";

        //处理整数部分
        BigDecimal res = new BigDecimal(0);
        int curIndex = 0;
        int baseIndex = 0; //根据万、亿调整
        for (int i = IntegerPart.length() - 1; i >= 0; i--) {
            char c = IntegerPart.charAt(i);
            if(isSuffix(c)){
                if(c == '万'){
                    baseIndex += 4;
                    curIndex = baseIndex;
                }
                else if(c == '亿'){
                    baseIndex = (baseIndex + 8) / 8 * 8;
                    curIndex = baseIndex;
                }
                else
                    curIndex = baseIndex + GetIndex(c);
            }
            else if(isNum(c))
                res = res.add(BigDecimal.valueOf(UpperToSingleNum(c) * Math.pow(10, curIndex)));
        }
        //处理小数部分
        if(!DecimalPart.equals("整") && !DecimalPart.equals(""))
            for (int i = DecimalPart.length() - 1; i >= 0 ; i--) {
                char c = DecimalPart.charAt(i);
                if (isSuffix(c))
                    curIndex = GetIndex(c);
                else if (isNum(c))
                    res = res.add(BigDecimal.valueOf(UpperToSingleNum(c) * Math.pow(10, curIndex)));
            }

        return res.setScale(2,BigDecimal.ROUND_HALF_DOWN).toString();
    }

    //判断为大写的数字
    private boolean isNum(char c){
        return c == '零'|| c == '壹'|| c == '贰'|| c == '叁'|| c == '肆'|| c == '伍'
                || c == '陆'|| c == '柒'|| c == '捌'|| c == '玖';
    }

    //判断为大写的后缀
    private boolean isSuffix(char c){
        return c == '亿' || c == '万' || c == '拾' || c == '仟' || c == '佰' || c == '圆'
                || c == '角' || c == '分';
    }

    //根据后缀名得到阶数
    private int GetIndex(char c){
        switch (c){
            case '仟':
                return 3;
            case '佰':
                return 2;
            case '拾':
                return 1;
            case '角':
                return -1;
            case '分':
                return -2;
        }
        return 0;
    }

    //根据大写数字获取对应小写
    private int UpperToSingleNum(char upper){
        switch (upper){
            case '零':
                return 0;
            case '壹':
                return 1;
            case '贰':
                return 2;
            case '叁':
                return 3;
            case '肆':
                return 4;
            case '伍':
                return 5;
            case '陆':
                return 6;
            case '柒':
                return 7;
            case '捌':
                return 8;
            case '玖':
                return 9;
        }
        return 0;
    }
}
